# gestur_sensor
# 使用toget函数获取手势
# 不要把gesinit与getges合并
import utime
from math import fabs
from machine import I2C,Pin
i2c=I2C(1,sda=Pin(0),scl=Pin(1),freq=400000)

def gesinit():
    i2c.write(57,b'\x81\xfc')
    i2c.write(57,b'\x8f\x01')
    i2c.write(57,b'\x80\x00')
    utime.sleep_ms(30)
    i2c.write(57,b'\x80\x01')
    utime.sleep_ms(30)
    i2c.write(57,b'\xa2\x40')
    i2c.write(57,b'\xA3\x40')
    i2c.write(57,b'\xA0\x32')
    i2c.write(57,b'\xA6\xc9')
    i2c.write(57,b'\x80\x05')
    i2c.write(57,b'\x80\x45')
    i2c.write(57,b'\xab\x01')
def getges():
    gesinit()
    dcount=ucount=lcount=rcount=0
    while 1:
        ges=''
        ud_diff=lr_diff=0
        while 1:
            if (i2c.readfrom_mem(57,0xaf,1)[0]==0):
                continue
            else:
                ae=i2c.readfrom_mem(57,0xae,1)
                if (ae==0):
                    continue
                gesture_num=i2c.readfrom_mem(57,0xfc,ae[0])
                container=i2c.readfrom_mem(57,0xfc,4)
                break
        if fabs(container[0]-container[1])>50:
            ud_diff+=container[0]-container[1]
        if fabs(container[2]-container[3])>50:
            lr_diff+=container[2]-container[3]

        if ud_diff!=0:
            if ud_diff<0:
                if dcount>0:
                    ges='down'
                else:
                    ucount+=1
            elif ud_diff>0:
                if ucount>0:
                    ges='up'
                else:
                    dcount+=1
        if lr_diff!=0:
            if lr_diff<0:
                if rcount>0:
                    ges='right'
                else:
                    lcount+=1
            if lr_diff>0:
                if lcount>0:
                    ges='left'
                else:
                    rcount+=1
        if ges!='':
            ucount=dcount=lcount=rcount=0
            # print(ges)
            return ges
def toget():
    while True:
        ges=getges()
        if ges:
            break
        utime.sleep_ms(500) #延迟控制
    print(ges)
    return ges